You are given an array nums consisting of positive integers.
Starting with score = 0, apply the following algorithm:
Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.
Add the value of the chosen integer to score.
Mark the chosen element and its two adjacent elements if they exist.
Repeat until all the array elements are marked.
Return the score you get after applying the above algorithm.
題目要我們對一組數組nums進行以下運算,記錄到score中最後返回:
我的解題思路:
public class Solution {
public int findScore(int[] nums) {
int n = nums.length;
boolean[] marked = new boolean[n];
int score = 0;
while (true) {
int min = -1; // 記錄最小值的序號
// 開始遍歷數列
for (int i = 0; i< n ; i++) {
if (!marked[i]) {
if (min == -1 || nums[i] < nums[min]) {
min = i;
}
}
}
if (min == -1) {
break;
}
score += nums[min];
marked[min] = true;
if (min > 0) {
marked[min - 1] = true; // 標記左邊
}
if (min < n - 1) {
marked[min + 1] = true; // 標記右邊
}
}
return score;
}
}
有點忘記是跟哪次的題目有點像了,總之今天的題目比昨天輕鬆太多了...
改了一些小錯誤之後成功結束這回合。